from flask import Blueprint, jsonify, request, g
import json
from loguru import logger
from app.err_no import errno_no
import traceback
from app.db import dbDiningQuery
from app.db.mongoClient import MongoError


blueprint = Blueprint('dining_query', __name__, url_prefix='/api/dining')


@blueprint.route('v1/query_all', methods=['POST'])
def query_all():
    '''
    查询所有餐厅、餐次
    '''
    try:
        if g.userType == 'stall':
            return jsonify(errno_no.ErrServerPermissionDenied.data(None))

        if g.userType == 'all':
            data = dbDiningQuery.queryAllDining()
        elif g.userType == 'dining':
            data = dbDiningQuery.queryDinings(g.RelationDiningNoList)

        return jsonify(errno_no.OK.data({'diningList': data}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('v1/query', methods=['POST'])
def dining_query():
    '''
    查询指定餐厅、餐次
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        if diningNo is None or len(diningNo) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        # 2021/11/06 此处不需要做判断，查询时可能是新建的，未来得及关联
        # 判断要查询的餐厅是不是他管辖范围内的
        # flag = False
        # for v in g.RelationDiningNoList:
        #     if v == diningNo:
        #         flag = True

        # if flag is False:
        #     return jsonify(errno_no.ErrServerPermissionDenied.data(None))

        data = dbDiningQuery.querySignDining(diningNo)

        return jsonify(errno_no.OK.data(data))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('v1/name_search', methods=['POST'])
def name_search():
    '''
    餐厅模糊搜索
    '''
    try:
        j_data = json.loads(request.data)
        diningName = j_data.get('diningName')
        if diningName is None:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbDiningQuery.nameSearch(diningName)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data({"diningList": res}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
